package jpa.dsl.boot.action;

import jpa.dsl.boot.model.Student;
import jpa.dsl.boot.repository.StudentRepository;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

// https://lufficc.com/blog/spring-boot-jpa-querydsl
@RestController
public class UserAction {
    @Autowired
    private StudentRepository studentRepository;
    //Spring 参数支持解析 com.querydsl.core.types.Predicate，
    // 根据用户请求的参数自动生成 Predicate，这样搜索方法不用自己写啦

    // /posts?name=name01  /posts?id=2
    // /posts?school.name=sch1（你没看错，可以嵌套，访问关系表中父类属性）   /posts?school.id=2&school.name=sch2
    @GetMapping("posts")
    public Object posts(@QuerydslPredicate(root = Student.class) Predicate predicate) {
        return studentRepository.findAll(predicate);
    }

    // 或者顺便加上分页
    @GetMapping("posts")
    public Object posts(@QuerydslPredicate(root = Student.class) Predicate predicate, Pageable pageable) {
        return studentRepository.findAll(predicate, pageable);
    }
}
